import React, { useEffect, useState } from 'react';
import { createElement } from 'react';
import { Table, Input, Button, Space, Form, InputNumber, message, Popconfirm, Row, Divider, Col, Card } from 'antd';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import './index.scss';

export interface NotificationTableProps {
    getUrl?: string;
}

const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{
                        margin: 0,
                    }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

const NotificationTable: React.FC<NotificationTableProps> = function NotificationTable({
    getUrl,
    ...otherProps
}) {
    const { TextArea } = Input;
    const [updateForm] = Form.useForm();
    const [insertForm] = Form.useForm();
    const [materialInsertForm] = Form.useForm();
    const [searchTerm, setSearchTerm] = React.useState("");
    const [messageApi, contextHolder] = message.useMessage();
    const [data, setData] = useState([
        {
            id: 1,
            code: 'test',
            name: 'test',
            purchaseNumber: 'test',
            vendorName: 'test',
            contact: '',
            phone: '11111111111',
            date: '2025-4-2',
            state: 'todo',
        },
        {
            id: 2,
            code: 'aa',
            name: 'aa',
            purchaseNumber: 'aa',
            vendorName: 'aa',
            contact: 'aa',
            phone: '11111111111',
            date: '2025-4-2',
            state: 'draft',
        },
        {
            id: 3,
            code: 'bb',
            name: 'bb',
            purchaseNumber: 'bb',
            vendorName: 'bb',
            contact: 'bb',
            phone: '11111111111',
            date: '2025-4-2',
            state: 'done',
        },
        {
            "searchValue": null,
            "createBy": "",
            "createTime": "2025-04-08 17:18:57",
            "updateBy": "",
            "updateTime": null,
            "remark": "",
            "params": {},
            "id": 7,
            "code": "AN20250408002",
            "name": "2",
            "purchaseNumber": null,
            "vendorId": 201,
            "vendorCode": "V00009",
            "vendorName": "江苏南通塑有为塑料制品有限公司",
            "vendorNick": "南通有为",
            "date": "2025-04-08",
            "contact": null,
            "phone": null,
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "",
            "createTime": "2025-04-08 17:18:50",
            "updateBy": "",
            "updateTime": null,
            "remark": "",
            "params": {},
            "id": 6,
            "code": "AN20250408001",
            "name": "1",
            "purchaseNumber": null,
            "vendorId": 201,
            "vendorCode": "V00009",
            "vendorName": "江苏南通塑有为塑料制品有限公司",
            "vendorNick": "南通有为",
            "date": "2025-04-08",
            "contact": null,
            "phone": null,
            "state": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "createTime": "2025-03-27 10:25:39",
            "updateBy": "",
            "updateTime": "2025-04-08 11:16:41",
            "remark": "",
            "params": {},
            "id": 5,
            "code": "AN20250327002",
            "name": "供应商江苏南通塑有为塑料制品有限公司到货通知单",
            "purchaseNumber": "PO01",
            "vendorId": 201,
            "vendorCode": "V00009",
            "vendorName": "江苏南通塑有为塑料制品有限公司",
            "vendorNick": "南通有为",
            "date": "2025-03-27",
            "contact": null,
            "phone": null,
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "createTime": "2025-03-27 10:22:00",
            "updateBy": "",
            "updateTime": "2025-03-27 10:22:22",
            "remark": "",
            "params": {},
            "id": 4,
            "code": "AN20250327001",
            "name": "供应商江苏南通塑有为塑料制品有限公司到货通知单",
            "purchaseNumber": "PO202503271001",
            "vendorId": 201,
            "vendorCode": "V00009",
            "vendorName": "江苏南通塑有为塑料制品有限公司",
            "vendorNick": "南通有为",
            "date": "2025-03-27",
            "contact": "李四",
            "phone": "13299106672",
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "",
            "createTime": "2025-03-12 18:48:06",
            "updateBy": "",
            "updateTime": "2025-03-12 18:50:11",
            "remark": "",
            "params": {},
            "id": 3,
            "code": "AN20250312005",
            "name": "辅材到货通知",
            "purchaseNumber": "PO10001",
            "vendorId": 202,
            "vendorCode": "GZDM",
            "vendorName": "DUOMU",
            "vendorNick": "DUOMU",
            "date": "2025-03-12",
            "contact": "王五",
            "phone": "1330000000",
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "",
            "createTime": "2025-03-12 16:45:16",
            "updateBy": "",
            "updateTime": "2025-03-12 18:12:04",
            "remark": "",
            "params": {},
            "id": 2,
            "code": "AN20250312003",
            "name": "注塑原料到货通知",
            "purchaseNumber": "PO202503011001",
            "vendorId": 203,
            "vendorCode": "V00038",
            "vendorName": "乙方工厂",
            "vendorNick": "1",
            "date": "2025-03-12",
            "contact": "李四",
            "phone": "13300000001",
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "",
            "createTime": "2025-03-12 15:46:41",
            "updateBy": "",
            "updateTime": "2025-03-12 15:59:35",
            "remark": "",
            "params": {},
            "id": 1,
            "code": "AN20250312002",
            "name": "钢筋到货通知",
            "purchaseNumber": "PO2025-03-01-1001",
            "vendorId": 212,
            "vendorCode": "V00068",
            "vendorName": "XXXX钢铁",
            "vendorNick": "XXXX钢铁有限公司",
            "date": "2025-03-12",
            "contact": "张三",
            "phone": "13200001111",
            "state": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        }

    ])

    const [materialData, setMaterialData] = useState([
        {
            id: 1,
            code: "aaa",
            name: 'aaa',
            unit: '个',
            amount: '100',
            note: '备注',
            specification: '4090'
        }
    ])
    const [currentPage, setCurrentPage] = useState(1);
    const pageSize = 5; // 每页显示5条数据

    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record) => record.id === editingKey;

    const resetSearch = () => {
        setSearchTerm("");
        // 这里恢复初始数据
    };

    const [isModalVisible1, setIsModalVisible1] = useState(false);

    const showModal1 = () => {
        setIsModalVisible1(true);
    };

    const hideModal1 = () => {
        setIsModalVisible1(false);
    };

    const onFinish1 = (values: any) => {
        console.log('Success:', values);
        hideModal1();
    };

    const [isModalVisible2, setIsModalVisible2] = useState(false);

    const showModal2 = (record) => {

        updateForm.setFieldsValue({
            code: '',
            name: '',
            purchaseNumber: '',
            vendorName: '',
            contact: '',
            phone: '',
            date: '',
            state: '',
            ...record,
        });
        setIsModalVisible2(true);
    };

    const hideModal2 = () => {
        setIsModalVisible2(false);
    };

    const onFinish2 = (values: any) => {
        console.log('Success:', values);
        hideModal2();
    };

    const [isModalVisible3, setIsModalVisible3] = useState(false);

    const showModal3 = () => {
        setIsModalVisible3(true);
    };

    const hideModal3 = () => {
        setIsModalVisible3(false);
    };

    const onFinish3 = (values: any) => {
        console.log('Success:', values);
        hideModal3();
    };


    const columns = [
        {
            title: '通知单编号',
            dataIndex: 'code',
            key: 'code',
            render: (text, record) => (
                <a style={{ color: '#1890ff' }} onClick={() => showModal2(record)}>
                    {text}
                </a>
            ),
            editable: true
        },
        {
            title: '通知单名称',
            dataIndex: 'name',
            key: 'name',
            editable: true,
        },
        {
            title: '采购订单号',
            dataIndex: 'purchaseNumber',
            key: 'purchaseNumber',
            editable: true,
        },
        {
            title: '供应商名称',
            dataIndex: 'vendorName',
            key: 'vendorName',
            editable: true,
        },
        {
            title: '联系人',
            dataIndex: 'contact',
            key: 'contact',
            editable: true,
        },
        {
            title: '联系方式',
            dataIndex: 'phone',
            key: 'phone',
            editable: true,
        },
        {
            title: '到货日期',
            dataIndex: 'date',
            key: 'date',
            editable: true,
        },
        {
            title: '单据状态',
            dataIndex: 'state',
            key: 'state',
            editable: true,
            render: (_,record) =>{
                if(record.state === 'todo'){
                    return(<>待入库</>)
                }else{
                    return(<>已完成</>)
                }
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => {
                if (record.state === 'todo') {
                    return (
                        <Space size="middle">
                            {isEditing(record) ? (
                                <>
                                    <Button type="link" onClick={() => save(record.id)}>保存</Button>
                                    <Popconfirm title="确定要取消吗？" onConfirm={cancel}>
                                        <Button type="link">取消</Button>
                                    </Popconfirm>
                                </>
                            ) : (
                                <>
                                    {/**********************************************
                                onClick里一定要写箭头函数 否则会在渲染时调用函数 */}
                                    <a href="#" onClick={() => showModal2(record)}><EditOutlined /> 编辑</a>
                                    <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                                        <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                                    </Popconfirm>

                                </>
                            )}
                        </Space>
                    );
                } else if (record.state === 'done') {
                    return (<></>);
                }

            },
        },
    ];

    const materialColumns = [
        {
            title: '物料编码',
            dataIndex: 'code',
            key: 'code',
            editable: true,
        },
        {
            title: '物料名称',
            dataIndex: 'name',
            key: 'name',
            editable: true,
        },
        {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            editable: true,
        },
        {
            title: '规格型号',
            dataIndex: 'specification',
            key: 'specification',
            editable: true,
        },
        {
            title: '到货数量',
            dataIndex: 'amount',
            key: 'amount',
            editable: true,
        },
        {
            title: '备注',
            dataIndex: 'note',
            key: 'note',
            editable: true,
        },
    ]


    const handleSearch = () => {
        // 假设我们做一个简单的搜索，只搜索 `code` 或 `name` 字段
        const filteredData = data.filter(
            (item) =>
                item.code.includes(searchTerm) || item.name.includes(searchTerm)
        );
        setData(filteredData);
    };



    const edit = (record) => {
        updateForm.setFieldsValue({
            code: '',
            name: '',
            purchaseNumber: '',
            vendorName: '',
            contact: '',
            phone: '',
            date: '',
            state: '',
            ...record,
        });
        setEditingKey(record.id);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (key) => {
        try {
            const row = await updateForm.validateFields();
            console.log("update row:", row);
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.id);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey('');

            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const deleteRow = (key) => {
        const newData = data.filter((item) => item.id !== key);
        setData(newData);

    };

    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                inputType: col.dataIndex === 'frozen' ? 'switch' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
                onSave: save,
            }),
        };
    });




    return (
        <>
            {contextHolder}
            <Row>
                <Space style={{ marginBottom: 16, marginTop: 20, marginLeft: 20 }}>
                    <Input
                        placeholder="请输入通知单编号或名称"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        style={{ width: 200 }}
                    />
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={resetSearch}>
                        重置
                    </Button>

                    <Button type="primary" onClick={showModal1}>
                        + 新增
                    </Button>
                    {isModalVisible1 && (
                        <div className="modal-overlay">
                            <div className="modal-content">
                                <Space direction="vertical" style={{ width: '100%', marginTop: 40 }}>

                                    <Form form={insertForm} name="InsertForm" onFinish={onFinish1} layout="vertical" labelAlign='left'>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="通知单编号" name="code">
                                                    <Input placeholder="通知单编号" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="通知单名称" name="name">
                                                    <Input placeholder="通知单名称" />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="采购单编号" name="purchaseNumber">
                                                    <Input placeholder="采购单编号" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="供应商" name="vendorName">
                                                    <Input placeholder="供应商" />
                                                </Form.Item>
                                            </Col>



                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={8}>
                                                <Form.Item label="到货日期" name="date">
                                                    <Input placeholder="到货日期" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="联系人" name="contact">
                                                    <Input placeholder="联系人" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="联系方式" name="phone">
                                                    <Input placeholder="联系方式" />
                                                </Form.Item>
                                            </Col>



                                        </Row>



                                        <Form.Item>
                                            <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                                                <Button onClick={hideModal1}>取消</Button>
                                                <Button type="primary" htmlType="submit" >提交</Button>
                                            </Space>
                                        </Form.Item>
                                    </Form>
                                    {/* <Space style={{ marginLeft: 30, marginTop: 16 }} direction="horizontal">
                                        <Button onClick={hideModal}>取消</Button>
                                        <Button type="primary" onClick={hideModal}>
                                            提交
                                        </Button>
                                    </Space> */}

                                    <span className="close-button" onClick={hideModal1}>&times;</span>
                                </Space>
                            </div>
                        </div>
                    )}
                    {isModalVisible2 && (
                        <div className="modal-overlay">
                            <div className="modal-content">
                                <Space direction="vertical" style={{ width: '100%', marginTop: 40 }}>

                                    <Form form={updateForm} name="updateForm" onFinish={onFinish2} layout="vertical" labelAlign='left'>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="通知单编号" name="code">
                                                    <Input placeholder="通知单编号" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="通知单名称" name="name">
                                                    <Input placeholder="通知单名称" />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="采购单编号" name="purchaseNumber">
                                                    <Input placeholder="采购单编号" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="供应商" name="vendorName">
                                                    <Input placeholder="供应商" />
                                                </Form.Item>
                                            </Col>



                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={8}>
                                                <Form.Item label="到货日期" name="date">
                                                    <Input placeholder="到货日期" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="联系人" name="contact">
                                                    <Input placeholder="联系人" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="联系方式" name="phone">
                                                    <Input placeholder="联系方式" />
                                                </Form.Item>
                                            </Col>



                                        </Row>
                                        <Divider>物料信息</Divider>
                                        <Card extra={<Button type="primary" onClick={showModal3}>新增</Button>}>
                                            <Table columns={materialColumns} dataSource={materialData}></Table>
                                        </Card>


                                        <Form.Item>
                                            <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                                                <Button onClick={hideModal2}>取消</Button>
                                                <Button type="primary" htmlType="submit" >提交</Button>
                                            </Space>
                                        </Form.Item>
                                    </Form>
                                    {/* <Space style={{ marginLeft: 30, marginTop: 16 }} direction="horizontal">
                                        <Button onClick={hideModal}>取消</Button>
                                        <Button type="primary" onClick={hideModal}>
                                            提交
                                        </Button>
                                    </Space> */}

                                    <span className="close-button" onClick={hideModal2}>&times;</span>
                                </Space>
                            </div>
                        </div>
                    )}
                    {isModalVisible3 && (
                        <div className="top-modal-overlay">
                            <div className="modal-content" style={{ width: 900 }}>
                                <Space direction="vertical" style={{ width: '100%', marginTop: 40 }}>

                                    <Form form={materialInsertForm} name="MaterialInsertForm" onFinish={onFinish3} layout="vertical" labelAlign='left'>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="物料编号" name="code">
                                                    <Input placeholder="物料编号" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="物料名称" name="name">
                                                    <Input placeholder="物料名称" />
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="单位" name="unit">
                                                    <Input placeholder="单位" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="到货数量" name="amount">
                                                    <InputNumber placeholder="amount" />
                                                </Form.Item>
                                            </Col>



                                        </Row>
                                        <Row gutter={16}>
                                            <Col span={12}>
                                                <Form.Item label="规格数量" name="specification">
                                                    <Input placeholder="规格数量" />
                                                </Form.Item>
                                            </Col>

                                        </Row>
                                        <Row>
                                            <Col span={24}>
                                                <Form.Item label="备注" name="note">
                                                    <TextArea placeholder="备注" rows={3} />
                                                </Form.Item>
                                            </Col>
                                        </Row>



                                        <Form.Item>
                                            <Space style={{ marginLeft: 350, marginTop: 16 }} direction="horizontal">
                                                <Button onClick={hideModal3}>取消</Button>
                                                <Button type="primary" htmlType="submit" >提交</Button>
                                            </Space>
                                        </Form.Item>
                                    </Form>
                                    {/* <Space style={{ marginLeft: 30, marginTop: 16 }} direction="horizontal">
                                        <Button onClick={hideModal}>取消</Button>
                                        <Button type="primary" onClick={hideModal}>
                                            提交
                                        </Button>
                                    </Space> */}

                                    <span className="close-button" onClick={hideModal3}>&times;</span>
                                </Space>
                            </div>
                        </div>
                    )}

                </Space>
            </Row >
            <Divider />
            <Form component={false}>
                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    dataSource={data.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
                    columns={mergedColumns}
                    rowClassName="editable-row"
                    pagination={{
                        total: data.length,
                        current: currentPage,
                        pageSize: pageSize,
                        onChange: (page) => {
                            setCurrentPage(page);
                            cancel();
                        },
                    }}
                />
            </Form>
        </>

    )
};

NotificationTable.displayName = '到货通知';
export default NotificationTable;


